package com.pudu.mydemo.fragment;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.pudu.mydemo.entity.AccessPoint;
import com.pudu.mydemo.view.ShowHidePasswordEditText;
import com.pudutech.pdrobot.R;

import fr.tvbarthel.lib.blurdialogfragment.BlurDialogFragment;

/**
 * Simple fragment with blur effect behind.
 */

/**
 * Created by guiliu on 2016/8/16.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class WifiLoginBlurDialogFragment extends BlurDialogFragment {


    /**
     * Bundle key used to start the blur dialog with a given scale factor (float).
     */
    private static final String BUNDLE_KEY_DOWN_SCALE_FACTOR = "bundle_key_down_scale_factor";

    /**
     * Bundle key used to start the blur dialog with a given blur radius (int).
     */
    private static final String BUNDLE_KEY_BLUR_RADIUS = "bundle_key_blur_radius";

    /**
     * Bundle key used to start the blur dialog with a given dimming effect policy.
     */
    private static final String BUNDLE_KEY_DIMMING = "bundle_key_dimming_effect";

    /**
     * Bundle key used to start the blur dialog with a given debug policy.
     */
    private static final String BUNDLE_KEY_DEBUG = "bundle_key_debug_effect";


    private static final String BUNDLE_KEY_TITLE = "bundle_key_title";
    private static final String BUNDLE_KEY_CONFIG = "bundle_key_config";

    private int mRadius;
    private float mDownScaleFactor;
    private boolean mDimming;
    private boolean mDebug;
    private String ssid;
    private boolean isConfig;
    private ImageButton cancel ,ok ;
    private ShowHidePasswordEditText password;
    private TextView wifiname;
    private  InputMethodManager inputMethodManager;
    /**
     * Retrieve a new instance of the sample fragment.
     *
     * @param radius          blur radius.
     * @param downScaleFactor down scale factor.
     * @param dimming         dimming effect.
     * @param debug           debug policy.
     * @return well instantiated fragment.
     */
    public static WifiLoginBlurDialogFragment newInstance(int radius,
                                                          float downScaleFactor,
                                                          boolean dimming,
                                                          boolean debug,
                                                          String ssid,
                                                          boolean isConfig
                                                         ) {


        WifiLoginBlurDialogFragment fragment = new WifiLoginBlurDialogFragment();
        Bundle args = new Bundle();
        args.putInt(
                BUNDLE_KEY_BLUR_RADIUS,
                radius
        );
        args.putFloat(
                BUNDLE_KEY_DOWN_SCALE_FACTOR,
                downScaleFactor
        );
        args.putBoolean(
                BUNDLE_KEY_DIMMING,
                dimming
        );
        args.putBoolean(
                BUNDLE_KEY_DEBUG,
                debug
        );
        args.putString(
                BUNDLE_KEY_TITLE,
                ssid
        );
        args.putBoolean(
                BUNDLE_KEY_CONFIG,
                isConfig
        );

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        Bundle args = getArguments();
        mRadius = args.getInt(BUNDLE_KEY_BLUR_RADIUS);
        mDownScaleFactor = args.getFloat(BUNDLE_KEY_DOWN_SCALE_FACTOR);
        mDimming = args.getBoolean(BUNDLE_KEY_DIMMING);
        mDebug = args.getBoolean(BUNDLE_KEY_DEBUG);
        ssid = args.getString(BUNDLE_KEY_TITLE);
        isConfig = args.getBoolean(BUNDLE_KEY_CONFIG);
        Log.e("guiliu","mRadius:"+mRadius);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("guiliu","getBlurRadius:"+getBlurRadius());
        super.onCreate(savedInstanceState);
        inputMethodManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

/*
    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.4), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
//        inputMethodManager.showSoftInput(password, InputMethodManager.SHOW_FORCED);

    }
*/

    /*
    *在onActivityCreated中修改屏幕宽高，软键盘依旧可以自动弹出，在onStart中却不行
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.4), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        inputMethodManager.showSoftInput(password, InputMethodManager.SHOW_FORCED);
//        password.setFocusable(true);
//        password.setFocusableInTouchMode(true);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getDialog() != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//            DisplayMetrics dm = new DisplayMetrics();
//            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//            getDialog().getWindow().setLayout((int) (dm.widthPixels * 0.3), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        View view = getActivity().getLayoutInflater().inflate(R.layout.wifi_login_dialog, null);
        cancel = (ImageButton)view.findViewById(R.id.cancel);
        ok = (ImageButton)view.findViewById(R.id.ok);
        password = (ShowHidePasswordEditText)view.findViewById(R.id.password);
        password.setTintColor(Color.RED);
        wifiname = (TextView)view.findViewById(R.id.wifi_name);
        wifiname.setText(ssid);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                LoginInputListener listener = (LoginInputListener) getActivity();
                listener.onLoginInputComplete(ssid,password
                        .getText().toString());
                dismiss();
            }
        });
        ok.setEnabled(false);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(password.getText().toString().length() >= 8) {
                    ok.setEnabled(true);
                } else {
                    ok.setEnabled(false);
                }
            }
        });
        return view;
    }
/*
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            View view = getActivity().getLayoutInflater().inflate(R.layout.wifi_login_dialog, null);
        cancel = (ImageView)view.findViewById(R.id.cancel);
        ok = (ImageView)view.findViewById(R.id.ok);
        password = (EditText)view.findViewById(R.id.password);
        wifiname = (TextView)view.findViewById(R.id.wifi_name);
        wifiname.setText(ssid);
        builder.setView(view);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                LoginInputListener listener = (LoginInputListener) getActivity();
                listener.onLoginInputComplete(ssid,password
                        .getText().toString());
                dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        return builder.create();
    }*/

    @Override
    protected boolean isDebugEnable() {
        return mDebug;
    }

    @Override
    protected boolean isDimmingEnable() {
        return mDimming;
    }

    @Override
    protected boolean isActionBarBlurred() {
        return true;
    }

    @Override
    protected float getDownScaleFactor() {
        return mDownScaleFactor;
    }

    @Override
    protected int getBlurRadius() {
        return mRadius;
    }

    public interface LoginInputListener
    {
        void onLoginInputComplete(String ssid, String password);
    }
}